package com.zhc.tools.demo.web.context;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Cookie助手类，提供cookie的读取和写入
 * 
 * @see javax.servlet.http.Cookie
 * @author zhc
 * 
 */
public class CookieUtils {
	
    private final static Log logger = LogFactory.getLog(CookieUtils.class);

    /**
     * 读取Cookie的值:直接返回cookie的值，不编码
     * 
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValueSimple(HttpServletRequest request, String name) {
        String value = null;
        Cookie cookie = CookieUtils.getCookieInfo(request, name);
        if (cookie != null) {
            value = cookie.getValue();
            logger.debug("Found '' cookie value [" + value + "]");
        } else {
            logger.trace("No '{" + name + "}' cookie value");
        }
        return value;
    }

    /**
     * 读取Cookie的值，返回使用Base64解码后的值
     * 
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        String sourceValue = CookieUtils.getCookieValueSimple(request, name);
        String value = null;
        if (sourceValue != null) {
            try {
                value = new String(Encodes.decodeBase64(sourceValue),"utf-8");
//                value = new String(java.net.URLDecoder.decode(sourceValue, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error("getCookieValue error:" + e);
            }
            logger.debug("Found '' cookie value [" + value + "]");
        } else {
            logger.trace("No '{" + name + "}' cookie value");
        }
        return value;
    }

    private static Cookie getCookieInfo(HttpServletRequest request, String cookieName) {
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 写入Cookie
     * 
     * @param response
     * @param name
     * @param value
     * @param domain
     * @param path
     */
    public static void setCookie(HttpServletResponse response, String name, String value, String domain, String path) {
        Cookie cookie = null;
        try {
//            cookie = new Cookie(name, java.net.URLEncoder.encode(value, "UTF-8"));
            cookie = new Cookie(name, new String(Encodes.encodeBase64(value.getBytes(),"UTF-8")));
        } catch (UnsupportedEncodingException e) {
            logger.error("setCookie error:" + e);
        }
        cookie.setDomain(domain);
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    /**
     * 设置cookie失效
     * 
     * @param response
     * @param name
     * @param domain
     * @param path
     */
    public static void invalidateCookie(HttpServletResponse response, String name, String domain, String path) {
        Cookie cookie = new Cookie(name, "");
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(0); // 使cookie失效
        response.addCookie(cookie);
    }

}
